package sv_tcp

import (
	"fmt"
	"strconv"
	"venus/core"
	"venus/service/sv_tcp/znet"
	"venus/service/sv_tcp/znet/zpack"
	"venus/service/sv_tcp/znet/ztcp"
	"venus/util/zhash"
)

// OnMsgReceive 接收到消息
// @receiver w
// @param request
func (sv *SvTcp) OnMsgReceive(conn *ztcp.TcpConnection, msg *zpack.PackBuffer) {
	//得到当前客户端请求的Request数据
	request := &znet.Request{
		Conn: conn,
		Msg:  msg,
	}
	if sv.MsgHandleDoSpeedy(request) {
		return
	}
	addMsg(request)
}

// TcpMsgHandleDo
// @Description:
// @param request
func (sv *SvTcp) TcpMsgHandleDo(request *znet.Request) {
	handler, ok := sv.TcpBinds[request.GetMsgID()]
	if !ok {
		fmt.Println("Handle msgId = ", request.GetMsgID(), " is not FOUND!")
		return
	}
	//执行对应处理方法
	handler(request)
}

// MsgHandleDoSpeedy
// @Description:
// @receiver w
// @param request
// @return bool
func (sv *SvTcp) MsgHandleDoSpeedy(request *znet.Request) bool {
	handler, ok := sv.TcpBindsSpeedy[request.GetMsgID()]
	if ok {
		//执行对应处理方法
		handler(request)
		return true
	}
	return false
}

// TcpWorkerBind 绑定
// @param pid
// @param handle
func (sv *SvTcp) TcpWorkerBind(msg interface{}, handle func(*znet.Request) int) {
	msgId := zhash.MsgHash(msg)
	//1 判断当前msg绑定的API处理方法是否已经存在
	if _, ok := sv.TcpBinds[msgId]; ok {
		panic("repeated api , pid = " + strconv.Itoa(int(msgId)))
	}
	//2 添加msg与api的绑定关系
	sv.TcpBinds[msgId] = handle
	fmt.Println("TcpWorkerBind pid = ", msgId, " msgId = ", msgId)
}

// TcpWorkerBindSpeedy
// @Description:
// @param pid
// @param handle
func (sv *SvTcp) TcpWorkerBindSpeedy(msg interface{}, handle func(*znet.Request) int) {
	msgId := zhash.MsgHash(msg)
	//1 判断当前msg绑定的API处理方法是否已经存在
	if _, ok := sv.TcpBindsSpeedy[msgId]; ok {
		panic("repeated api , pid = " + strconv.Itoa(int(msgId)))
	}
	//2 添加msg与api的绑定关系
	sv.TcpBindsSpeedy[msgId] = handle
	fmt.Println("TcpWorkerBindSpeedy pid = ", msgId, " msgId = ", msgId)
}

func addMsg(request *znet.Request) {
	msg := &core.Msg{
		Type: core.MsgTypeTcpRequest,
		Data: request,
	}
	core.AddMsg(msg)
}
